import axios from "axios";
import { getToken, removeToken } from '@/utils/auth'
import { ElMessageBox } from 'element-plus';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建简化版的请求配置
const service = axios.create({
    // baseURL: 'http://dev-api.nuojinsheng.com',
    timeout: 10000
});
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 请求拦截器
service.interceptors.request.use(config => {
    // 自动携带 token
    if (getToken() && config.headers?.isToken !== false) {
        config.headers.Authorization = `Bearer ${getToken()}`;
    }

    // 防重复提交逻辑
    if ((config.method === 'post' || config.method === 'put') && config.headers?.repeatSubmit !== false) {
        const requestKey = JSON.stringify({
            url: config.url,
            data: config.data
        });
        const lastRequest = sessionStorage.getItem('lastRequest');
        if (lastRequest && requestKey === lastRequest) {
            return Promise.reject(new Error('请勿重复提交请求'));
        }
        sessionStorage.setItem('lastRequest', requestKey);
    }

    return config;
}, error => Promise.reject(error));

// 响应拦截器(保持现有结构,仅优化状态处理)
service.interceptors.response.use(response => {
    // 处理二进制响应
    if (response.config.responseType === 'blob') {
        return response;
    }
    // 简化状态码处理
    const { code, msg } = response.data;
    switch (code) {
        case 200:
            return response.data;
        case 401:
            return handle401Error(msg);
        default:
            ElMessageBox.confirm(msg || '请求异常');
            return Promise.reject(msg);
    }
}, error => {
    // 统一错误处理
    const errMsg = error.response?.data?.msg || error.message;
    ElMessageBox.confirm(errMsg || '网络异常');
    return Promise.reject(error);
});

// 单独封装的401处理
function handle401Error(msg) {
    ElMessageBox.confirm(msg || '登录状态已过期', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        removeToken()
        window.location.href = '/login';
    });
    return Promise.reject('登录过期');
}

export default service;
